//
//  BKGDImagesView.m
//  BESTKEEP
//
//  Created by 武探 on 2016/10/8.
//  Copyright © 2016年 YISHANG. All rights reserved.
//

#import "BKGDImagesView.h"
#import "BKGDCommon.h"

#define BKGDImagesViewColumnsCount 3
#define BKGDImagesViewLineSpace 5

NSString *const BKGDImagesViewItemScreenRect = @"BKGDImagesViewItemScreenRect";
NSString *const BKGDImagesViewItemImage = @"BKGDImagesViewItemImage";
NSString *const BKGDImagesViewItemIndex = @"BKGDImagesViewItemIndex";

@interface BKGDImagesViewCell : UICollectionViewCell;

@property(nonatomic,strong) UIImageView *imageView;

@end

@implementation BKGDImagesViewCell

-(instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame: frame];
    if(self) {
        [self initialize];
    }
    
    return self;
}

-(void)initialize {
    _imageView = [[UIImageView alloc] init];
    _imageView.contentMode = UIViewContentModeScaleAspectFill;
    _imageView.clipsToBounds = YES;
    [self.contentView addSubview:_imageView];
}

-(void)layoutSubviews {
    [super layoutSubviews];
    
    _imageView.frame = self.bounds;
}

@end





NSString *const BKGDImagesViewCellIdentifier = @"BKGDImagesViewCellIdentifier";

@interface BKGDImagesView()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@property(nonatomic,strong) UICollectionView *collectionView;
@property(nonatomic,strong) UILabel *bottomRightLabel;
@property(nonatomic,assign) BOOL isAutoLayout;

@end

@implementation BKGDImagesView

-(instancetype)initWithAutoLayout:(BOOL)isAutoLayout {
    self = [super initWithFrame:CGRectMake(0, 0, 320, 80)];
    if(self) {
        _isAutoLayout = isAutoLayout;
        [self initialize];
    }
    return self;
}

-(instancetype)initWithFrame:(CGRect)frame {
    
    if(CGRectEqualToRect(CGRectZero, frame)) {
        frame = CGRectMake(0, 0, 320, 80);
    }
    
    self = [super initWithFrame:frame];
    if(self) {
        _isAutoLayout = YES;
        [self initialize];
    }
    return self;
}

-(void)initialize {
    
    _maxShowCount = NSNotFound;
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.minimumLineSpacing = BKGDImagesViewLineSpace;
    layout.minimumInteritemSpacing = BKGDImagesViewLineSpace;
    
    _collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:layout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.showsHorizontalScrollIndicator = NO;
    _collectionView.alwaysBounceVertical = NO;
    _collectionView.alwaysBounceHorizontal = NO;
    _collectionView.backgroundColor = [UIColor clearColor];
    [_collectionView registerClass:[BKGDImagesViewCell class] forCellWithReuseIdentifier:BKGDImagesViewCellIdentifier];
    [self addSubview:_collectionView];
    
    if(_isAutoLayout) {
        _collectionView.bounces = NO;
    } else {
        _collectionView.bounces = YES;
        
        _collectionView.contentInset = UIEdgeInsetsMake(0, 12, 0, 20);
    }
    
    _bottomRightLabel = [[UILabel alloc] init];
    _bottomRightLabel.backgroundColor = [UIColor blackColor];
    _bottomRightLabel.textColor = [UIColor whiteColor];
    _bottomRightLabel.font = [UIFont systemFontOfSize:10];
    _bottomRightLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    _bottomRightLabel.layer.masksToBounds = YES;
    _bottomRightLabel.textAlignment = NSTextAlignmentCenter;
    _bottomRightLabel.layer.cornerRadius = 2;
    _bottomRightLabel.hidden = YES;
    [self addSubview:_bottomRightLabel];
}

-(void)layoutSubviews {
    [super layoutSubviews];
    _collectionView.frame = self.bounds;
    
    [self updateBottomRightLabelLayout];
}

#pragma -mark collectionView delegate
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    NSInteger count = 0;
    if(_images) {
        
        if(_maxShowCount != NSNotFound) {
            count = _images.count > _maxShowCount ? _maxShowCount : _images.count;
        } else {
            count = _images.count;
        }
    }
    
    return count;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if(_isAutoLayout) {
        CGFloat space = (BKGDImagesViewColumnsCount - 1) * BKGDImagesViewLineSpace;
        CGFloat width = (CGRectGetWidth(self.frame) - space) / BKGDImagesViewColumnsCount;
        return CGSizeMake(width, width);
    } else {
        return CGSizeMake(64, CGRectGetHeight(self.frame));
    }
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    BKGDImagesViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:BKGDImagesViewCellIdentifier forIndexPath:indexPath];
    
    NSString *path = _images[indexPath.row];
    [cell.imageView load:path placeholderImage:[UIImage imageNamed:@"BKGDDefaultBig"]];
    
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    BKGDImagesViewCell *cell = (BKGDImagesViewCell*)[collectionView cellForItemAtIndexPath:indexPath];
    
    if(_delegate && [_delegate respondsToSelector:@selector(imagesView:didSelectAtIndex:atImage:)]) {
        [_delegate imagesView:self didSelectAtIndex:indexPath.row atImage:cell.imageView.image];
    }
}

-(void)setImages:(NSArray<NSString *> *)images {
    _images = images;
    
    [_collectionView.collectionViewLayout invalidateLayout];
    [_collectionView reloadData];
}

/**
 布局右下角信息栏
 */
-(void)updateBottomRightLabelLayout {
    CGRect brRect = CGRectZero;
    if(_isShowMaxCountMessage && _images && _maxShowCount != NSNotFound && _images.count > _maxShowCount) {
        
        _bottomRightLabel.hidden = NO;
        
        NSString *brMessage = [NSString stringWithFormat:@"%@%ld%@", BKGDLocalizedString(@"BKGDImagesTotal"), (long)_images.count, BKGDLocalizedString(@"BKGDImagesUnit")];
        _bottomRightLabel.text = brMessage;
        
        if(brMessage && ![brMessage isEqualToString:@""]) {
            CGSize brSize = [brMessage sizeWithAttributes:@{NSFontAttributeName: _bottomRightLabel.font}];
            CGFloat brWidth = brSize.width + 4;
            CGFloat brHeight = 14;
            brRect = CGRectMake(CGRectGetWidth(self.frame) - brWidth - 2, CGRectGetHeight(self.frame) - brHeight - 2, brWidth, brHeight);
        }
    } else {
        _bottomRightLabel.hidden = YES;
        _bottomRightLabel.text = @"";
    }
    
    _bottomRightLabel.frame = brRect;
}

-(CGRect)rectToScreenAtItemIndex:(NSInteger)index {
    
    UICollectionViewCell *cell = [_collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
    if(cell) {
        UIWindow *window = [[UIApplication sharedApplication] keyWindow];
        CGRect rect = [cell convertRect:cell.contentView.frame toView:window];
        return rect;
    }
    return CGRectZero;
}

-(NSDictionary *)propertyWithPoint:(CGPoint)point {
    
    CGPoint p = [self convertPoint:point toView:_collectionView];
    
    NSIndexPath *indexPath = [_collectionView indexPathForItemAtPoint:p];
    if(!indexPath) {
        return nil;
    }
    
    UIView *view = [[UIApplication sharedApplication] keyWindow];
    
    BKGDImagesViewCell *cell = (BKGDImagesViewCell*)[_collectionView cellForItemAtIndexPath:indexPath];
    UIImage *image = cell.imageView.image;
    if(!image) {
        return nil;
    }
    
    CGRect rect = [cell convertRect:cell.contentView.frame toView:view];
    
    NSInteger index = indexPath.row;
    
    NSDictionary *dict = @{BKGDImagesViewItemScreenRect: [NSValue valueWithCGRect:rect], BKGDImagesViewItemImage: image, BKGDImagesViewItemIndex: @(index)};
    
    return dict;
}

@end
